package com.atguigu.yygh.sms.controller.front;

import cn.hutool.core.lang.Validator;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.sms.service.SmsService;
import com.atguigu.yygh.sms.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2022/12/29 - 09:20
 * @Author: Hyoung
 * @Description:
 */


@Api(tags = "短信接口")
@RestController
@RequestMapping("/front/sms")
public class FrontSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("发送短信")
    @PostMapping("/send/{phone}")
    public R code(@PathVariable String phone) {

        // 手机号校验

        boolean isMobile = Validator.isMobile(phone);
        if (!isMobile) {
            throw new YyghException(ResultCodeEnum.LOGIN_MOBILE_ERROR);
        }

        //生成验证码
        String code = RandomUtil.getFourBitRandom();
        //发送短信
        smsService.send(phone, code);

        //验证码存入redis，并设置有效时间
        redisTemplate.opsForValue().set("code:" + phone, code, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}